package com.dsl.dslsuzhou.common;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.dsl.dslsuzhou.model.dto.os.TypePram;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ConnectUtils {


    /**
     * @param url 地址
     * @param type 调用类型 (:Method.Get)
     * @param header 调用的请求头
     * @return
     */
    public HttpResponse getExecute(String url, TypePram type, Map<String, ?>... header) {
        HttpRequest httpRequest = new HttpRequest(url);
        httpRequest.setMethod(type.getMethod());
        if (Method.POST.equals(type.method) || Method.PUT.equals(type.method)){
            httpRequest.body(type.getBody());
        }
        if (header.length > 0) {
            for (Map<String, ?> entry : header) {
                entry.forEach((key, value) -> {
                    httpRequest.header(key, String.valueOf(value));
                });
            }
        }
        HttpResponse execute = httpRequest.execute();
        return execute;
    }

    /**
     * @description: 拼接url地址
     * url ：请求地址  paramMap 要拼接的path参数
     **/
    public  String generateUrlPath(String url,Map<String, ?> paramMap) {
        String collect = paramMap.entrySet().stream()
                .map(e -> e.getKey() + "=" + e.getValue())
                .collect(Collectors.joining("&"));
        return url+"?"+collect;
    }
}
